import {computed} from 'vue'

export const useUserProfile = (props, mappingProps, emit, { C_Emits, publicMethod }) => {

  const profileParam = computed(() => {
    return {
      profileKeys: {
        Key: `fasr-popupfilter`,
        DynamicKey: `${props.instanceCode}_${props.userProfileSuffix}`,
      },
      PageID: props.pageID,
    };
  });


  /* @ts-ignore */
  const { GetPageUserProfile, SetPageUserProfile } = Funcs;

  function getUserProfile() {
    if (props.enableUserProfile && GetPageUserProfile) {
      GetPageUserProfile(profileParam.value).then(res => {
        const { data, errcode, errmsg, state } = res;
        if ('1' == state) {
          data.forEach(profile => {
            if (profile.ConfigValue) {
              mappingProps.userConfigProps = JSON.parse(profile.ConfigValue);
            }
          });
        }
      });
    }
  }
  function saveUserProfile(profileValue) {
    if (props.enableUserProfile && SetPageUserProfile) {
      SetPageUserProfile({
        PageID: profileParam.value.PageID,
        profileKey: profileParam.value.profileKeys,
        profileValue: JSON.stringify(profileValue),
      }).then(res => {
      });
    }
  }

  function emitUserProfileChange() {
    emit(C_Emits.UserProfileChange, {
      profile: publicMethod.getUserProfile(),
    });
  }

  return {
    profileParam,
    getUserProfile,
    saveUserProfile,
    emitUserProfileChange,
  };
};
